package com.glsc.ngateway.platform.controller.other;

import cn.hutool.core.util.StrUtil;
import com.glsc.ngateway.common.base.domain.mysql.gateway.other.Tag;
import com.glsc.ngateway.common.base.domain.mysql.gateway.other.TagProdRel;
import com.glsc.ngateway.common.base.domain.mysql.gateway.other.UpdateAllRef4TagDto;
import com.glsc.ngateway.common.api.platform.dto.other.TagProdRelDto;
import com.glsc.ngateway.platform.service.other.TagService;
import com.glsc.ngateway.common.api.common.enums.DictConstant;
import com.glsc.ngateway.platform.utils.JsonTool;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.common.ex.Result;
import com.querydsl.core.QueryResults;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author libj
 * @date 2021/2/2
 * 标签管理
 */
@RestController
@RequestMapping("/api/tag/")
@Api(value = "标签管理", tags = {"标签管理"})
public class TagController {

    private static Logger logger = LoggerFactory.getLogger(TagController.class);

    @Resource
    private TagService tagService;

    /**
     * 创建标签信息
     */
    @PostMapping("/create")
    @ApiOperation(value = "创建标签信息", notes = "创建标签信息")
    public Map<String, Object> saveTag(@RequestBody Tag tag) {
        logger.info("创建标签信息:" + tag.toString());

        try {
            tag.setTagDeleted(DictConstant.NO);
            //填充操作用户ID
//            RequestTool.fillOpInfo(tag, DictConstant.OP_SOURCE_WEB, DictConstant.OP_ACTION_ADD);
            tagService.saveTag(tag);
            return Result.success("创建标签信息成功");
        } catch (Exception e) {
            logger.error("Error", e);
            return Result.fail(Result.CODE_ERROR_10002, "创建标签信息失败:" + e.getMessage());
        }
    }

    /**
     * 更新标签信息
     */
    @PostMapping("/update")
//    @RequiredPermission("/api/tag/update")
    @ApiOperation(value = "更新标签信息", notes = "更新标签信息")
    public Map<String, Object> updateTag(@RequestBody Tag tag) {
        try {
            Tag orginal = tagService.findById(tag.getTagId());
            if (null == orginal) {
                return Result.fail("获取标签信息失败");
            }
            orginal.setTagName(tag.getTagName());
            orginal.setTagGroup(tag.getTagGroup());
            orginal.setSortNo(tag.getSortNo());
            orginal.setSelectProdMethod(tag.getSelectProdMethod());
            orginal.setSelectProdSql(tag.getSelectProdSql());
            orginal.setRemark(tag.getRemark());
            orginal.setTagCode(tag.getTagCode());
            //填充操作用户ID
//            RequestTool.fillOpInfo(tag, DictConstant.OP_SOURCE_WEB, DictConstant.OP_ACTION_UPDATE);
            tagService.saveTag(orginal);
            return Result.success("修改标签信息成功");
        } catch (Exception e) {
            logger.error("失败",e);
            return Result.fail("修改标签信息失败:" + e.getMessage());
        }
    }

    /**
     * 删除标签信息
     */
    @PostMapping("/delete")
//    @RequiredPermission("/api/tag/delete")
    @ApiOperation(value = "删除标签信息", notes = "删除标签信息")
    public Map<String, Object> deleteRole(@ApiParam(required = true, value = "标签id") @RequestBody String jsonId) {
        Integer tagId = JsonTool.parseJsonIdStr(jsonId);
        if (tagId < 0) {
            return Result.fail("id参数错误");
        }
        Tag tag = tagService.findById(tagId);
        if (null == tag || DictConstant.YES.equals(tag.getTagDeleted())) {
            return Result.fail("删除标签Id为" + tagId + "的标签信息不存在或者已经是删除状态");
        }
        tag.setTagDeleted(DictConstant.YES);
        tag.setOpAction(DictConstant.OP_ACTION_DELETE);
        tagService.saveTag(tag);
        return Result.success("删除标签信息成功");
    }

    /**
     * 按照产品Id查询标签信息
     */
    @GetMapping("/getTagByProdId")
    @ApiOperation(value = "按照产品Id查询标签信息", notes = "按照产品Id查询标签信息")
    public Result<Tag> getTagByProdId(@ApiParam(value = "产品Id") @RequestParam(required = true) Integer prodId) {
        logger.info("getTagByProdId: 按照产品Id查询标签信息");
        try {
            return Result.successData(tagService.findByProdId(prodId));
        } catch (Exception e) {
            logger.error("查询标签信息列表，原因：" + e.getMessage(),e);
            return Result.failData("查询标签信息列表，原因：" + e.getMessage());
        }
    }

    /**
     * 按照tagId查询标签信息
     */
    @GetMapping("/getTagByTagId")
    @ApiOperation(value = "按照tagId查询标签信息", notes = "按照tagId查询标签信息")
    public Result<Tag> getTagByTagId(@ApiParam(value = "标签id") @RequestParam(required = false) Integer id) {
        logger.info("getTagByTagId: 按照tagId查询标签信息");
        try {
            return Result.successData(tagService.findById(id));
        } catch (Exception e) {
            logger.warn("查询标签信息列表，原因：" + e.getMessage());
            return Result.failData("查询标签信息列表，原因：" + e.getMessage());
        }
    }

    /**
     * 分页查询标签信息
     */
    @GetMapping("/tagpage")
    @ApiOperation(value = "查询标签信息分页")
    public Result<QueryResults<Tag>> tagpage(
            @ApiParam(value = "标签名称") @RequestParam(required = false) String tagName,
            @ApiParam(value = "标签分组") @RequestParam(required = false) String tagGroup,
            @ApiParam(value = "产品配置方式") @RequestParam(required = false) String selectProdMethod,
            @ApiParam(value = "标签编码") @RequestParam(required = false) String tagCode,
            @ApiParam(value = "页码从1开始") @RequestParam(required = false) Integer pageNo,
            @ApiParam(value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("EQ_tagDeleted", DictConstant.NO);
        if (StrUtil.isNotBlank(tagName)) {
            queryParam.put("LIKE_tagName", tagName);
        }
        if (StrUtil.isNotBlank(tagGroup)) {
            queryParam.put("EQ_tagGroup", tagGroup);
        }
        if (StrUtil.isNotBlank(selectProdMethod)) {
            queryParam.put("EQ_selectProdMethod", selectProdMethod);
        }
        if (StrUtil.isNotBlank(tagCode)) {
            queryParam.put("LIKE_tagCode", tagCode);
        }
        Page<Tag> page = tagService.findPage(PageUtil.initPageNo(pageNo), PageUtil.initPageSize(pageSize), queryParam);
        return Result.successData(page);
    }

    @GetMapping("/getSelectedProductList")
    @ApiOperation(value = "查询选中产品列表", notes = "查询选中产品列表")
    public Result<List<TagProdRelDto>> getSelectedProductList(@ApiParam(value = "标签id") @RequestParam(required = false) Integer id) {
        logger.info("getSelectedProductList: 查询选中产品列表");
        try {
            return Result.successData(tagService.getSelectedProductList(id));
        } catch (Exception e) {
            logger.warn("查询选中产品列表，原因：" + e.getMessage());
            return Result.failData("查询选中产品列表，原因：" + e.getMessage());
        }
    }

    /**
     * 保存分配产品标签信息
     */
    @PostMapping("/updateAllRef4Tag")
//    @RequiredPermission("/api/tag/updateAllRef4Tag")
    @ApiOperation(value = "保存分配产品标签信息", notes = "保存分配产品标签信息")
    public Map<String, Object> updateAllRef4Tag(@RequestBody UpdateAllRef4TagDto dto) {
        try {
            List<TagProdRel> refs = new ArrayList<>();
            for(Integer prodId:dto.getProdIds()) {
                TagProdRel ref = new TagProdRel();
                ref.setTagId(dto.getTagId());
                ref.setProdId(prodId);
                refs.add(ref);
            }
            tagService.deleteTagProdRefByTagId(dto.getTagId());
            tagService.saveAllRef4Tag(refs);
            return Result.success("保存分配产品标签信息成功");
        } catch (Exception e) {
            logger.error("失败",e);
            return Result.fail("保存分配产品标签信息失败:" + e.getMessage());
        }
    }

    /**
     * 刷新自动分配产品标签信息
     */
    @PostMapping("/refresh")
//    @RequiredPermission("/api/tag/refresh")
    @ApiOperation(value = "刷新自动分配产品标签信息", notes = "刷新自动分配产品标签信息")
    public Map<String, Object> refresh(@ApiParam(required = true, value = "标签id") @RequestBody String jsonId) {
        Integer tagId = JsonTool.parseJsonIdStr(jsonId);
        if (tagId < 0) {
            return Result.fail("id参数错误");
        }
        try {
            tagService.refresh(tagId);
            return Result.success("刷新自动分配产品标签信息成功");
        } catch (Exception e) {
            logger.error("失败",e);
            return Result.fail("刷新自动分配产品标签信息失败:" + e.getMessage());
        }
    }

    /**
     * 刷新自动分配产品标签信息
     */
    @GetMapping("/searchAll")
//    @RequiredPermission("/api/tag/refresh")
    @ApiOperation(value = "单一关键字全局搜索", notes = "单一关键字全局搜索")
    public Result<Map> searchAll(@ApiParam(required = true, value = "标签id")@RequestParam(required = true) String key) {
        try {
            return Result.successData(tagService.searchAll(key));
        } catch (Exception e) {
            logger.error("失败",e);
            return Result.failData("搜索失败，原因：" + e.getMessage());
        }
    }
}
